package br.edu.faculdadeprojecao.DAO;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.edu.faculdadeprojecao.modelo.Professor;

public class ProfessorDAO {
	private EntityManager em;

	public ProfessorDAO(EntityManager em) {
		this.em = em;
	}

	public void salva(Professor p) {
		em.persist(p);
	}

	public void altera(Professor p) {
		em.merge(p);
		System.out.println("dao professor" + p.getId());
	}

	public void delete(Professor p) {
		em.remove(p);

	}

	public Professor busca(Integer id) {
		return em.find(Professor.class, id);

	}

	public Professor buscaPorNome(String nome) {
		String jpql = "select p from Professor p where p.usuario.nome=:nome";
		Query query = em.createQuery(jpql);
		query.setParameter("nome", nome);

		Professor professor = (Professor) query.getSingleResult();

		return professor;
	}
	
	public Professor buscaPorMatricula(String mat) {
		String jpql = "select p from Professor p where p.usuario.matricula=:mat";
		Query query = em.createQuery(jpql);
		query.setParameter("mat", mat);

		Professor professor = (Professor) query.getSingleResult();

		return professor;
	}

	public List<Professor> lista() {

		String jpql = "select p from Professor p where p.ativo=:ativo order by p.usuario.nome asc";
		Query query = this.em.createQuery(jpql);
		query.setParameter("ativo", true);
		@SuppressWarnings("unchecked")
		List<Professor> list = query.getResultList();

		return list;
	}

	public List<Professor> listaAsc() {

		String jpql = "select p from Professor p where p.ativo=:ativo order by p.usuario.nome asc";
		Query query = this.em.createQuery(jpql);
		query.setParameter("ativo", true);
		@SuppressWarnings("unchecked")
		List<Professor> list = query.getResultList();

		return list;
	}

	public Professor buscaPorNomeEMatricula(String nome, String matricula) {
		String jpql = "select p from Professor p where p.usuario.nome=:nome and p.usuario.matricula=:matricula";
		Query query = em.createQuery(jpql);
		query.setParameter("nome", nome);
		query.setParameter("matricula", matricula);
		Professor professor = (Professor) query.getSingleResult();
		return professor;
	}

}
